using System;
using System.Collections.Generic;
using OpenFlashChartLib.Json;

namespace OpenFlashChartLib.Charts
{
    public class Chart<T> : ChartBase where T : ILabelValue, new()
    {
        private IList<ILabelValue> _valuesInterface;

        public Chart()
        {
            InternalValues = new List<T>();
            _valuesInterface = new ValuesCollection<T>(InternalValues);
            Fillalpha = 0.35;
        }

        [JsonProperty("values")]
        public override IList<ILabelValue> Values
        {
            get { return _valuesInterface; }
            set
            {
                if (value == null)
                {
                    _valuesInterface = null;
                    InternalValues.Clear();
                }
                else if (value != _valuesInterface)
                {
                    InternalValues.Clear();
                    foreach (var labelValue in value)
                    {
                        InternalValues.Add((T)labelValue);
                    }
                    _valuesInterface = new ValuesCollection<T>(InternalValues);
                }
            }
        }

        public override ILabelValue NewValue()
        {
            return new T();
        }

        public override ILabelValue NewValue(string label, double value)
        {
            return new T() {Label = label, Value = value};
        }

        public override double GetMaxValue()
        {
            if (InternalValues.Count == 0)
                return 0;
            double max = double.MinValue;
            foreach (ILabelValue d in InternalValues)
            {
                if (d.Value > max)
                    max = d.Value;
            }
            return max;
        }

        public override int GetValueCount()
        {
            return InternalValues.Count;
        }

        public override double GetMinValue()
        {
            if (InternalValues.Count == 0)
                return 0;
            double min = double.MaxValue;
            Type valuetype = typeof (T);
            if (!valuetype.IsValueType)
                return 0;
            foreach (T d in InternalValues)
            {
                double temp = double.Parse(d.ToString());
                if (temp < min)
                    min = temp;
            }
            return min;
        }

        public void AppendValue(T v)
        {
            InternalValues.Add(v);
        }

        public virtual void Set_Key(string text, double font_size)
        {
            Text = text;
            Fontsize = font_size;
        }

        protected IList<T> InternalValues
        {
            get; set;
        }
    }
}